from pandas import *
import pandas as pd
#import henry_charting
import smartcharting
import matplotlib.pyplot as plt
import datetime
#import twintowers
import time
import os

strtoday = datetime.datetime.now().strftime("%Y-%m-%d")
SLEEPTIME = 300
inputdir='C:\\_src\\twintower\\twintower\\'

outputdir_='C:\\Users\\Public\\_tt\\TickStats\\'
outputdir = "{}{}".format(outputdir_,strtoday)
if not os.path.exists(outputdir):
    print "create "+outputdir
    os.makedirs(outputdir)

#files = ["athm-{}.lst".format(strtoday)] #"hmin-20140324.lst",

ss = ["ATHM","HMIN"] #"hmin-20140324.lst",


for i in range(200):
    for symbol in ss:
        try:
          inputfile = "{}-{}.lst".format(symbol, strtoday)

          fpath=inputdir+inputfile
          if not os.path.exists(fpath):
              print "ERROR:"+fpath+" doesnt exist!!"
              continue
          else:
              print "reading "+fpath
          header_row=['dt','master','slave','ask', 'bid', 't1', 't2', 't3', 't4', 'spread']
          p1=pd.read_csv(fpath,index_col=0,parse_dates=True,dayfirst=True, names=header_row, usecols=[0,3,4,5,6,7,8,9])
          if len(p1)==0:
              print "EMPTY FILE:" + fpath
              continue
          c=p1.spread
          ax1 = plt.subplot(311)
          plt.title("spread of "+symbol + '@' + datetime.datetime.now().strftime("%Y-%m-%d-%H:%M:%S"))
          plt.setp(ax1.get_xticklabels(), visible=True)
          c.hist(bins=np.arange(c.min(),c.max(),(c.max()-c.min())/200),color='g',alpha=0.4)
          
          ax2 = plt.subplot(312)
          #plt.title("ask")
          plt.setp(ax2.get_xticklabels(), visible=True)
          c=p1.ask
          c.hist(bins=np.arange(c.min(),c.max(),(c.max()-c.min())/200),color='r',alpha=0.4)
          
          ax3 = ax2
          #plt.title("bid")
          plt.setp(ax3.get_xticklabels(), visible=True)
          c=p1.bid
          c.hist(bins=np.arange(c.min(),c.max(),(c.max()-c.min())/200),color='b',alpha=0.4)
          
          ax4 = plt.subplot(313)
          #plt.title("bid")
          plt.setp(ax4.get_xticklabels(), visible=True)
          p1.bid.plot(ax=ax4,style='o-')
          p1.ask.plot(ax=ax4,style='o-')
          
          """
          ax5 = plt.subplot(414)
          #plt.title("ask")
          plt.setp(ax5.get_xticklabels(), visible=True)
          c=p1.ask-p1.bid
          c.plot(ax=ax5,style='-')
          """
          
          pngfile='{s0}/{s1}-{t}.png'.format(s0=outputdir,s1=symbol,t=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
          plt.savefig(pngfile)

          output_stats_file="{}-{}-stats.lst".format(symbol, strtoday)
          fpath2=outputdir_ + output_stats_file
          f = open(fpath2,"a+")
          f.write(str(p1[['bid','ask']].describe()))
          f.close()
          
          #plt.show()
          plt.clf()
        except Exception as e:
          s = str(e)
          print "Exception:",s

    time.sleep(SLEEPTIME)